<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Dcat\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Watson\Rememberable\Rememberable;

class Category extends Model
{

    use Rememberable;

    protected $rememberCacheTag = 'category_cache';

    protected $cache_expire_in_minutes = 1440;
    use ModelTree;
    use HasDateTimeFormatter;
    // use SoftDeletes;
    
    const STATUS = ['未审核','已通过','驳回'];
    protected $table = 'category';
    protected $titleColumn = 'title';

    protected $orderColumn = 'sort';

    protected $parentColumn = 'parent_id';
    public $timestamps = true;
    protected $dateFormat = 'U';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    protected $hidden = [
        'type',
        'sort'
    ];

    public function project()
    {
        return $this->belongsToMany(Project::class);
    }

    /**
     * 获取分类列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-09
     * @param array $where
     * @param string $field
     * @return mixed
     */
    public function getList($where, $field = ['*'])
    {

        $where = function ($query) use ($where) {

            $query->where('is_del', 0);
            $query->where('status', 1);
            $query->where('parent_id', 1);

            if (isset($where['name']) && $where['name'] != '') {
                $query->where('title', 'like', '%' . $where['name'] . '%');
            }

            if (isset($where['type']) && $where['type'] != '') {
                $query->where('parent_id', $where['type']);
            }
            
            if (isset($where['category_ids']) && $where['category_ids'] != '') {
                $query->whereIn('id', $where['category_ids']);
            }
        };
        $model = new self();
        return $model->where($where)->remember($this->cache_expire_in_minutes)->select($field)->get();
    }
}
